package handlers

import (
	"github.com/gin-gonic/gin"
	"short-video1/models"
	"strconv"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	title := c.PostForm("title")
	img := c.PostForm("img")
	userID, _ := strconv.Atoi(c.PostForm("user_id"))
	data := models.File{
		Name:      name,
		Title:     title,
		Img:       img,
		UserID:    userID,
		FileCount: 0,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	query := models.DB.Model(&models.File{})
	offset := (page - 1) * size
	var count int64
	query.Count(&count)
	var film []models.File
	err := models.DB.Limit(size).Offset(offset).Order("file_count desc").Find(&film).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "列表展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": gin.H{
			"film":  film,
			"count": count,
		},
	})
	return
}
func CollFilmList(c *gin.Context) {
	userID := c.Query("user_id")
	var film []models.File
	err := models.DB.Where("user_id", userID).Order("coll_count desc").Find(&film).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": film,
	})
	return
}
